<?php

class User
{
    private $pdo;

    /**
     * 构造方法
     * User constructor.
     * @param $pdo pdo实例对象
     */
    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }


    /**
     * 用户登录
     * @param $username
     * @param $password
     * @return
     */
    public function login($username, $password)
    {
        if (empty($username)) {
            self::_throw_exception('用户名不能为空', ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        if (empty($password)) {
            self::_throw_exception('密码不能为空', ErrorCode::PASSWORD_CANNOT_EMPTY);
        }
        $sql = 'SELECT * FROM `user` WHERE `username`=:username AND `password`=:password';
        $password = $this->_md5($password);
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam('username',$username);
        $stmt->bindParam('password',$password);
        if (!$stmt->execute()){
            throw new Exception('服务器内部错误',ErrorCode::SERVER_INTERNAL_ERROR);
        }
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (empty($user)){
            self::_throw_exception('用户名或密码错误',ErrorCode::USERNAME_OR_PASSWORD_INVALID);
        }
        unset($user['password']);
        return $user;
    }

    /**
     * 用户注册
     * @param $username
     * @param $password
     * @return array
     */
    public function register($username, $password)
    {
        if (empty($username)) {
            self::_throw_exception('用户名不能为空', ErrorCode::USERNAME_CANNOT_EMPTY);
        }
        if (empty($password)) {
            self::_throw_exception('密码不能为空', ErrorCode::PASSWORD_CANNOT_EMPTY);
        }
        if ($this->_isUsernameExists($username)) {
            self::_throw_exception('用户名已存在', ErrorCode::USERNAME_EXISTS);
        }
        // 新增用户名和密码到数据库中
        $sql = 'INSERT INTO `user`(`username`,`password`,`create_dt`) VALUES (:username, :password, :create_dt)';
        $create_dt = time();
        $password = $this->_md5($password);
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam('username', $username);
        $stmt->bindParam('password', $password);
        $stmt->bindParam('create_dt', $create_dt);
        if (!$stmt->execute()) {
            self::_throw_exception('注册失败', ErrorCode::REGISTER_FAILED);
        }
        return [
            'user_id' => $this->pdo->lastInsertId(),
            'username' => $username,
            'create_dt' => $create_dt,
        ];
    }

    /**
     * MD5加密
     * @param $string
     * @param string $key
     * @return string
     */
    public function _md5($string, $key = 'king')
    {
        return md5($string . $key);
    }

    /**
     * 判断用户名是否存在
     * @return bool
     */
    private function _isUsernameExists($username)
    {
        $sql = 'SELECT * FROM `user` WHERE `username`=:username';
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam('username', $username);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return !empty($result);
    }

    private static function _throw_exception($errMsg, $errCode)
    {
        die($errMsg . ' - ErrorCode：' . $errCode);
    }
}